package org.ch02.job.test12;

import java.lang.reflect.Field;

/**
 * @author XCH
 * @date 2025 - 03 - 19
 */
public class BeanUtil {
    //1、设置何意对象的属性值
    public static void setProperty(Object bean, String propertyName, Object value){
        try {
            Field field = bean.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            field.set(bean, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //2、获取任意对象的属性值
    public static Object getProperty(Object bean, String propertyName){
        try {
            Field field = bean.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            return field.get(bean);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //3、复制某个对象的属性值到另一个对象中
    public static void copyProperties(Object source, Object target){
        try {
            Field[] fields = source.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(source);
                field.set(target, value);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
